/* kernel/kmlog.c 
 * 
 * Copyright (C) 2021, 2022 intirain. 
 *
 * This file is part of evx. 
 * 
 * evx is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * evx is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with evx. If not, see <https://www.gnu.org/licenses/>
 */ 




#include <kernel/init.h>
#include <kernel/module.h>
#include <kernel/kernel.h>
#include <kernel/kmlog.h>
#include <kernel/tty.h>

#include <arch/archinfo.h>
#include <arch/string.h>

#include <sys/types.h>
#include <stdarg.h>


/* write log to memory, before printk is ready.
 *
 * kmlog buffer sets by arch_mm_init (why it is always this 
 * function...) and **MUST** be cleared by it. 
 *
 * the buffer is always in the kernel heap, and it's always 
 * KMLOG_SIZE bytes long.*/


char 	*kmlog_buf;
int 	kmlog_index = 1;

int kmlog(char *s, ...) {
	int len, i, level;
	char buf[512];
	va_list args;


	memset(buf, 0, 512);
	va_start(args, s);

	if (*s == '#') {
		if ((level = atoi(s[1])) < KMLOG_LEVEL) 
			return 0;

		s += 2;
	}

	len = vsprintf(buf, s, args);

	/* replace last zero */
	kmlog_index--;

	/* <= len copies a zero from buf */

	for (i = 0; i <= len; i++) {
		if (kmlog_index > KMLOG_SIZE) 
			kmlog_index = 0;

		kmlog_buf[kmlog_index++] = buf[i];
	}

	if (likely(init_state == STATE_READY))
		tty_write_all(buf);

	va_end(args);

	return 0;
}

